package com.luoxue.service;

import com.luoxue.entity.User;
import com.luoxue.mapper.UserMapper;
import com.luoxue.security.JwtTokenUtil;
import com.luoxue.util.MyException;
import com.luoxue.util.ResultBody;
import org.apache.logging.log4j.util.Strings;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserService implements UserDetailsService {
    @Resource
    UserMapper userMapper;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    public ResultBody login(String username, String password) throws MyException {
        if (Strings.isBlank(username)) {
            MyException.create("请求参数username为空或空字符串");
        }
        if (Strings.isBlank(password)) {
            MyException.create("请求参数password为空或空字符串");
        }
        User user = this.loadUserByUsername(username);
        if (Strings.isNotBlank(password) && user != null && Strings.isNotBlank(user.getPassword())) {
            if (DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
                jwtTokenUtil.addUser(user);
                return ResultBody.ok(jwtTokenUtil.generateToken(user));
            }
        }
        return MyException.create("登录失败");
    }

    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public ResultBody logout() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        jwtTokenUtil.removeUser(username);
        return ResultBody.ok(username + ", 注销成功");
    }

    @Override
    public User loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userMapper.getUserByUsername(userName);
        List<String> roleIdList = user.getRoleList().stream().map(role -> role.getId().toString()).collect(Collectors.toList());
        user.setRoleIds(String.join(",", roleIdList));
        return user;
    }

    public ResultBody getUser() {
        return ResultBody.ok(SecurityContextHolder.getContext().getAuthentication().getCredentials());
    }
}
